Ccay.Module.define("Ccay.SiteMap.ListSiteMap",function(page,$S){
	
	page.ready=function(){	
		
		$S("#btnAdd").ccayTip("ccay.sitemap.label.addTip");

	    var gridOption = {
	    	//percentWidth :true,
	    	editMode:true,
	    	showPager :false,
			rowRender: "tree",
			rowRenderOp: {
				parent: "parent.siteNodeId",
				field: "siteNodeId",
				showField: "name",
				sortData:true,
				select:"multi", // 单选 single
				loadDeep:10,
				lazyLoad:true,
				ajax: {
					url: "services/ccay/sitemap/tree/list?parentId={0}"
				},
				fnCheckParent:function(pid,node,datas){
				  return true;
			    }
			},
			contextMenu:true,
			menuOp:{
        		 menus:[{
        		 	// 导出 上下文的菜单
        		 	text:$i18n("ccay.common.button.export"),
        		    click:function(cell,menu){
						var rowData = $S("#listSiteMapIgrid").manager().getRowData(cell);
						Ccay.SiteMap.ListSiteMap.siteMapExport(rowData.siteNodeId);
					}
        		    }]
        	},
			showSeq: false,
			height:380,
			allowSort :false,
			// 设置igrid编辑之后的事件
			fnEndEdit: function (value, rowData, td) {
				// 只有”功能可用时“ 可编辑功能，否则为空
				if(rowData.control != 3){
					rowData.accessName = "";
					// 防止重新渲染，修改标识丢失
					var row = this.getCellRow(td);
				    row.find("td[field=accessName]").text("");
				};
			//	rowData["parent.siteNodeId"] != null && (rowData.parent.siteNodeId = rowData["parent.siteNodeId"]);
				return false;
			},
			fnBeforeEdit:function(value, td, col){
				// 得到行对象
				var row = this.getCellRow(td);
				// 得到行数据
				var rowData = this.getRowData(row);
				// 控制单元格是否可编辑
				if(rowData.control == 3 && col.field == "accessName"){
						return true;
				}
				if(rowData.control != 3 && col.field == "accessName"){
						return false;
				}
				if(rowData.siteNodeId == -1 && col.field == "parent.name"){
						return false;
				}
			},
	        columns: [
				//{columnType: "select",multi: false},
				{width: 200, field: 'name', header: 'ccay.sitemap.label.name',freezeable:true,rule: {required: true,maxlength:100,speczh:true},renderer:Ccay.UI.Renderer.create(showNameByLang)},
				{width: 50,  field: 'siteNodeId', header: 'ccay.sitemap.label.siteNodeId',editable:false,hidden:true},
				{width: 100, field: 'parent.name', valueField:"parent.siteNodeId",header: 'ccay.sitemap.label.parentId',rule: {required: true,maxlength:100},renderer:Ccay.UI.Renderer.create(showNameByLang2p),
				           rendererType: 'enum',
				           format:{valueField:"value",displayField:"text"},
				           editorOp: {
				              conf:{
				                    valueField:'siteNodeId',
				                    displayField:'name',
				                    title:"ccay.sitemap.selectparent",
				                    url:"services/ccay/sitemap/all/tree/full",
				                    treeSetting:{expandLevel:"0"}}}, editor: Ccay.Editor.create(popupTree)},
				{width: 100, field: 'url', header: 'ccay.sitemap.label.url',rule:{maxlength:1000},rendererType:"ellipsis",type:"textarea"},
		        {width: 50,  field: 'orderId',cssName:"right",  header: 'ccay.sitemap.label.orderId',rule:{max:9999999,min:0}},
		        {width: 115, field: 'control', cssName:"center", header: 'ccay.sitemap.label.control',type:"enum",format:{service:'FN:Ccay.SiteMap.ListSiteMap.getControlData',valueField: "value", displayField: "text"},rule: {required: true ,maxlength : 1000}},
		        {width: 100, field: 'accessName', header: 'ccay.sitemap.label.function',rendererType:"ellipsis",editorOp: {cssName: "grid-editor",conf:{valueField:'parentId',displayField:'name',callback:function(){}}}, editor: Ccay.Editor.create(popupPermissionTree)},
		        {width: 100, field: 'description', header: 'ccay.sitemap.label.description',type:"textarea",rendererType:"ellipsis",rule:{ maxlength : 1000}},
		        {width: 80,  field: 'target',cssName:"center",  header: 'ccay.sitemap.label.target',type:"enum",format:{service:'FN:Ccay.SiteMap.ListSiteMap.getTargetSource',valueField: "value", displayField: "text",valid:false},rule: {required: true}},
	            {width: 50,  field: 'status',cssName:"center",  header: 'ccay.sitemap.label.visible', type: 'enum',format:{service:'FN:Ccay.SiteMap.ListSiteMap.getStatus',valueField: "value", displayField: "text"}}
		    ],
	        ajax:{
	        	url:"services/ccay/sitemap/tree/list"
	        },
		    operation: {
		    	search: {
		    		btn: '#btnSearch',
					panel: '#searchForm'
		    	},
		    	del: {
		    		btn: '#btnDelete',
		    		undoBtn: '#btnUndoDelete'
		    	},
		    	insert: {
		    		btn: '#btnAdd',
		    		defaultRow:{name:"zh_CN=,en_US=",target:'_self', status:'2',control:'1',orderId:'0',parent:{siteNodeId:"-1"}}
		    	},
		    	save: {
		    		btn: '#btnSave',
		    		ajax: {
		    			url: "services/ccay/sitemap/batch/save"
		    		}
		    	}
		    }
	    };
		
	    $S("#listSiteMapIgrid").igrid(gridOption);		
	};	
	
	// 控制显示栏目
	page.getControlData=function(){
		return [{value:"1",text:$i18n("ccay.sitemap.label.visibleToEveryone")},
				{value:"2",text:$i18n("ccay.sitemap.label.visibleByChildren")},
				{value:"3",text:$i18n("ccay.sitemap.label.visibleToFunction")}
		]
	};
	
	// 打开方式
	page.getTargetSource = function() {
		return [{value:"_self", text:$i18n("ccay.sitemap.label.self")},
				{value:"_blank", text:$i18n("ccay.common.button.blank")},
				{value:"_contentFrame", text:$i18n("ccay.sitemap.label.iframe")},
				{value:"_website", text:$i18n("ccay.sitemap.label.website")}];
	};
	
    // 是否发布
	page.getStatus = function() {
		return [{value:"0", text:$i18n("ccay.common.label.no")},
				{value:"2", text:$i18n("ccay.common.label.yes")}];
	};
	
	// 栏目弹出树
	var popupTree = {
		build: function (container, op) {
			var ctr = $.create("input", "", $.newGuid("ctr_editor_"), "text").attr('readonly','true').appendTo(container);
			var btn = $.create("input", "jbutton", "", "button").attr("value", "...").appendTo(container);
			var bean = op.conf || {};
			btn.click(function () {
				ctr.data("ctr_locked", true);
                //Ccay.Component.popupTree = function(title,dataOrUrl,treeSetting,selectCallback,width,height,dialogOp)
				Ccay.Component.popupTree(bean.title,bean.url,bean.treeSetting,function(nodes){
					if(nodes.length>0){
						ctr.data("value", nodes[0][bean.valueField]).val( nodes[0][bean.displayField]);
					}
				},null,null,{fnClose:function(){
				     ctr.removeData("ctr_locked").focus();
				}});
			});
	        return ctr;
	    },
	    getValue: function (ctr) {
	    	return {
	    		value: ctr.data("value")|| "",
	    		text: ctr.val() || ""
	    	}
	    },
	    setValue: function (ctr, valueObj) {
	    	ctr.data("value",valueObj.value);
	        this.base.setValue.call(this, ctr,valueObj.text);
	    }
	};
	
	// 权限弹出树
	var popupPermissionTree = {
			build: function (container, op) {
				var ctr = $.create("input", "", $.newGuid("ctr_editor_"), "text").attr('readonly','true').appendTo(container);
				var btn = $.create("input", "jbutton", "", "button").attr("value", "...").appendTo(container);
				var bean = op.conf || {};
				btn.click(function () {
					ctr.data("ctr_locked", true);
					Ccay.Component.popPermissionTree(false, null, function(result){
						if(result.length>0){
							var treeNode = result[0].treeNode;
						    ctr.data("value", treeNode["resource"].resourceType+"$"+treeNode["resource"].resourceCode+"$"+treeNode["operationCode"]).val(treeNode["resource"].resourceType+"$"+treeNode["resource"].resourceCode+"$"+treeNode["operationCode"]);
					    };
					}, 
					ctr.data("value"),
					{beforeClose:function(){
					    ctr.removeData("ctr_locked").focus();
					}});
				});
		        return ctr;
		    },
		    getValue: function (ctr) {
		    	return ctr.val() || "";
		    },
		    setValue: function (ctr, value) {
		    	ctr.data("value", value);
		       this.base.setValue.call(this, ctr, value);
		    }
		};

	// 设置自定义验证器 特殊字符
	$.validator.addMethod("speczh", function(value, element, params){
		if(value){
			var reg=new RegExp("[<>?!@#$%\\\\\\/]+");
			return !reg.test(value) ? true : false;
		}
	}, $i18n("ccay.common.validate.speczh"));
	
	// 菜单弄成渲染
	page.languageRender = function(value) {
		if(value == null){
			return "";
		};
		if(value == "zh_CN=,en_US="){
			return value;
		};
		var nameLanguage = value.split(",");
		var language = workspaceVO.currentLanguage;
		for (var i = 0; i < nameLanguage.length; i++) {
			var lang = nameLanguage[i].split("=");
			if (lang.length > 1 && lang[0] == language) {
					return lang[1];
			}
		};
		return value;
	};
	
	// 节点名渲染器
	var showNameByLang = {
			type:"sitemap", // 树表showField和渲染的是同一列导致自定义渲染器无效，需加上type解决，任意字符串
			setOption:function(op) {
				op.valueField = op.field;
				this.base.setOption.call(this, op);
			},
			getFormat:function(field, format) {
				return "${#Ccay.SiteMap.ListSiteMap.languageRender({0})}".formatText(field);
			},
			render:function(target, value, format) {
				target.find(".child-render").html(this.format(value,format)).attr("title",value);
			},
			getValue:function(target) {
				return target.attr("val");
			}
	};
	
	// 父节点名渲染器
	var showNameByLang2p = {
			getFormat:function(field, format) {
				return "${#Ccay.SiteMap.ListSiteMap.languageRender({0})}".formatText(field);
			},
			getValue: function (target) {
		    	return {
		    		value: target.attr('val') || "",
		    		text: target.text() || ""
		    	};
			},
			format:function (value, format) {
		    	if(!format) format = {};
		    		return Ccay.SiteMap.ListSiteMap.languageRender(value);
		    },
			render:function(target, valueObj, format) {
				target.attr('val', valueObj.value);
				target.html(this.format(valueObj.text,format));
			}
	};
	
    // siteNode 导入
	page.siteMapImport=function(){
		var param={uploadType:"ExcelImport",
					completeCallback: Ccay.Component.Excel.uploadCallback,
					closeDialog:true,
					query:"excelType=ccay.sitemap.siteNode"};
		Ccay.Component.openUploadDialog($i18n("ccay.common.button.import"),param);
	}
	
    // siteNode 导出全部
	page.siteMapExport=function(nodeId){
		if(nodeId == null ){
			nodeId = 0;
		};
		Ccay.doGet("services/ccay/sitemap/list/export",{siteNodeId:nodeId},function(){
		    Ccay.Component.Excel.exportCallback();
		});
	};
	
});

